package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.WorkerManService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.common.page.Pagination;
import cn.buildoncloud.labor.workermanapplet.util.FileUtil;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import cn.buildoncloud.labor.workermanapplet.util.OCRUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnJava;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import sun.rmi.runtime.Log;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("workerman")
public class WorkerManController  {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${webSystemIP}")
    private String webSystemIP;

    @Autowired
    private WorkerManService workerManService;

    /**
     * 工友进退场-工友管理-列表
     * @param search
     * @param pageNumber
     * @param pageSize
     * @param pId
     * @return
     */
    @RequestMapping("/listWorkerMan")
    public Object listWorkerMan(@RequestParam(required = false) String search,
                                   @RequestParam int pageNumber,
                                   @RequestParam int pageSize,
                                   @RequestParam String pId){
        try{
            Pagination workerman = workerManService.listPageWorkerMan(search, pageNumber, pageSize, Long.parseLong(pId));
            return Result.success("", workerman);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("接口错误");
        }


    }

    @RequestMapping("/getWorkerMan")
    public Object getWorkerMan(@RequestParam String wId){
        try{
            Map<String, Object> map = workerManService.getWorkerMan(Long.parseLong(wId));
            return Result.success("", map);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(1, "参数错误");
        }
    }
    /**
     *@create 2019/1/14 16:20
     *@Param [wId, pageNo, pageSize]
     *@return java.lang.Object
     *@desc  查询工人  (新增了曾参与项目 分页+排序)
            */
    @RequestMapping("/getWorkerManProject")
    public Object getWorkerManProject(@RequestParam String wId ,
                                      @RequestParam(value = "pageNumber",defaultValue = "1") Integer pageNumber,
                                      @RequestParam(value = "pageSize",defaultValue = "2" ) Integer pageSize){

        try{
            List result = workerManService.getWorkerManProject(Long.parseLong(wId),pageNumber,pageSize);

            return Result.success("", result);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(1, "参数错误");
        }

    }

    @RequestMapping("/manOutProject")
    public Object manOutProject(@RequestParam("projectId") Long projectId,
                                @RequestParam("workerManId") Long workerManId,
                                @RequestParam("manSkillqualityScore") int manSkillqualityScore,
                                @RequestParam("manAppraise") String manAppraise,
                                @RequestParam("haveBadRecord") boolean haveBadRecord,
                                @RequestParam("manBadRecordDescription") String manBadRecordDescription){
        Map parameterMap = new HashMap<>();
        parameterMap.put("projectId", projectId);
        parameterMap.put("workerManId", workerManId);
        //评价
        parameterMap.put("evaluate", manAppraise);
        //评分
        parameterMap.put("score", manSkillqualityScore);
        //是否有不良记录``
        parameterMap.put("haveBadRecord", haveBadRecord);
        //不良记录描述
        parameterMap.put("badRecordNote", manBadRecordDescription);

        try{
            String result = HttpUtil.post(webSystemIP + "/business/workerman/manOutProject", parameterMap, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
//        Response response = Http.post2(webSystemIP + "/business/workerman/manOutProject", parameterMap, 1000 * 60);
//        Result result = Json.fromJson(Result.class, response.getContent());

    }

    @PostMapping("/saveManAndEnter")
    public Object saveManAndEnter(@RequestParam String workerTeamId,
                                  @RequestParam String name,
                                  @RequestParam String sex,
                                  @RequestParam String idCardNo,
                                  @RequestParam String nation,
                                  @RequestParam String birthDate,
                                  @RequestParam String address,
                                  @RequestParam String inDate,
                                  @RequestParam String tel,
                                  @RequestParam String workClassId,
                                  @RequestParam String workTypeId,
                                  @RequestParam(required = false) String emergencyContactTel,
                                  @RequestParam(required = false) String bloody,
                                  @RequestParam(required = false) String calculationOfSalary,
                                  @RequestParam(required = false) String calculationOfSalaryNote,
                                  @RequestParam(required = false) String bankAccount,
                                  @RequestParam(required = false) String openAccountBank,
                                  @RequestParam(required = false) String idCardOrg,
                                  @RequestParam(required = false) String isSuedData,
                                  @RequestParam(required = false) String idCardValidata,
                                  @RequestParam String projectId,
                                  @RequestParam String idCardPhotoPath,
                                  @RequestParam String headPhotoPath,
                                  @RequestParam String idCardPhotoFrontPath,
                                  @RequestParam String idCardPhotoReversePath){

        try{
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("workerTeamId", workerTeamId);
            parameterMap.put("name", name);
            parameterMap.put("sex", sex);
            parameterMap.put("idCardNo", idCardNo);
            parameterMap.put("nation", nation);
            parameterMap.put("birthDate", birthDate);
            parameterMap.put("address", address);
            parameterMap.put("inDate", inDate);
            parameterMap.put("tel", tel);
            parameterMap.put("workEx.workClassId", workClassId);
            parameterMap.put("workEx.workTypeId", workTypeId);
            parameterMap.put("emergencyContactTel", emergencyContactTel);
            parameterMap.put("bloody", bloody);
            parameterMap.put("calculationOfSalary", calculationOfSalary);
            parameterMap.put("calculationOfSalaryNote", calculationOfSalaryNote);
            parameterMap.put("bankAccount", bankAccount);
            parameterMap.put("openAccountBank", openAccountBank);
            parameterMap.put("idCardOrg", idCardOrg);
            parameterMap.put("isSuedData", isSuedData);
            parameterMap.put("idCardValidata", idCardValidata);
            parameterMap.put("projectId", projectId);
            parameterMap.put("idCardPhotoPath", idCardPhotoPath);
            parameterMap.put("headPhotoPath", headPhotoPath);
            Map<String, Object> workermanExistence = null;

            workermanExistence = workerManService.getWorkerManIdByIdCardNo(idCardNo);

            if (workermanExistence!= null){
                Long wId = Long.parseLong(workermanExistence.get("id").toString());
                parameterMap.put("id", wId);

                Map<String, Object> map = workerManService.getWorkerManTeamproject(wId, Long.parseLong(projectId));
                if (map != null){
                    return Result.error("工人已进场, 请勿重复进场. ");
                }
                String result = HttpUtil.post(webSystemIP + "/business/workerman/updManAndEnter", parameterMap, 1000 * 60);
                updateWorkerManIdCardPhoto(idCardNo, idCardPhotoFrontPath, idCardPhotoReversePath);
                return result;
            }

            String result = HttpUtil.post(webSystemIP + "/business/workerman/createManAndEnter", parameterMap, 1000 * 60);
            updateWorkerManIdCardPhoto(idCardNo, idCardPhotoFrontPath, idCardPhotoReversePath);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_FAILED_TO_ENTER);
        }
    }

    /**
     * 根据您身份证号--上传工友身份证正反面
     * @param idCardNo
     * @param idCardPhotoFrontPath
     * @param idCardPhotoReversePath
     */
    private void updateWorkerManIdCardPhoto(String idCardNo, String idCardPhotoFrontPath, String idCardPhotoReversePath){
        try{
            String[] filePath = new String[]{idCardPhotoFrontPath, idCardPhotoReversePath};
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("filePath", filePath);
            String result = HttpUtil.post(webSystemIP + "/fileupload/baseUploadFiles", parameterMap, 1000 * 60);
            log.error("result : " + result);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            List<Object> listData = (List<Object>) resultMap.get("data");
            Map<String, Object> result1 = (Map<String, Object>) listData.get(0);
            Map<String, Object> result2 = (Map<String, Object>) listData.get(1);
            workerManService.updateWorkerManIdCard(idCardNo, result1.get("id").toString(), result2.get("id").toString());
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    @RequestMapping("/uploadIdCard")
    public Object uploadIdCard(@RequestParam String base64File, @RequestParam String pId){
        //face/decorativeIdCardPhoto photo

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = new HashMap<>();
            Result result = OCRUtil.ocrIdCard(base64File);
            if (result.getData() != null){
                String dataJsonStr = objectMapper.writeValueAsString(result.getData());
                try{
                    data = objectMapper.readValue(dataJsonStr, HashMap.class);
                    if (data.get("idCardInfo") != null){
                        HashMap<String,Object> date10 = (HashMap<String, Object>) data.get("idCardInfo");
                        String idCardNo = (String)date10.get("id");


                        Map<String, Object> workermanExistence = workerManService.workerManIsEnter(idCardNo, Long.parseLong(pId));

                        if(workermanExistence != null){
                            return Result.error("工人已进场, 请勿重复进场");
                        }
                    }
                }
                catch (JsonMappingException e){}
                catch (JsonParseException e){}
                catch (IOException e){}
            }


            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("photo", base64File);
            String idCardPhotoResult = HttpUtil.post(webSystemIP + "/face/decorativeIdCardPhoto", parameterMap);


            Map<String, Object> idCardPhotoResultMap = objectMapper.readValue(idCardPhotoResult , HashMap.class);

            if (idCardPhotoResultMap.get("code") == null){
                return Result.error(Constant.API_NETWORK_ANOMALY);
            }

            Integer codeNum = Integer.parseInt(idCardPhotoResultMap.get("code").toString());
            if (codeNum != 0){
                return idCardPhotoResult;
            }
            Map<String, Object> dataMap = (Map) idCardPhotoResultMap.get("data");

            data.put("idCardPhoto", dataMap.get("ID_CARD_PHOTO").toString());
            data.put("idHeadPath", dataMap.get("ID_HEAD_PATH").toString());

            result.setData(data);
            return result;
//            Result result = OCRUtil.ocrIdCard(base64File);
//            return result;
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    @RequestMapping("/uploadIdCardReverse")
    public Object uploadIdCardReverse(@RequestParam String base64File){
        try {
            return upLoadBase64Jpg(base64File);
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    /**
     * 通过用户身份证获取工友基本信息
     * @param idCardNo
     * @return
     */
    @RequestMapping("/getWorkermanByIdCard")
    public Object getWorkermanByIdCard(@RequestParam String idCardNo){
        try{
            return workerManService.getWorkerManByIdCardNo(idCardNo);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

    @RequestMapping("/fileBase64Comparison")
    public Object fileBase64Comparison(@RequestParam String filePath,
                                        @RequestParam String face2){
        File file = new File(filePath);
        String face1 = FileUtil.fileToBase64(file);
        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("face1", face1);
        parameterMap.put("face2", face2);
//        Response response = Http.post2(webSystemIP + "/face/base64ToJpgComparison", parameterMap, 1000 * 60);
//        Result result = Json.fromJson(Result.class, response.getContent());
        try{
            String result = HttpUtil.post(webSystemIP + "/face/base64ToJpgComparison", parameterMap, 1000 * 60);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            Double comparison = (Double) resultMap.get("data");
            Map<String, Object> data = new HashMap<>();
            data.put("comparison", comparison);
            data.put("idHeadBase64", face1);
            resultMap.put("data", data);
            return resultMap;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

    @RequestMapping("/base64ToJpgComparison")
    public Object base64ToJpgComparison(@RequestParam String face1,
                                        @RequestParam String face2){

        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("face1", face1);
        parameterMap.put("face2", face2);
//        Response response = Http.post2(webSystemIP + "/face/base64ToJpgComparison", parameterMap, 1000 * 60);
//        Result result = Json.fromJson(Result.class, response.getContent());
        try{
            String result = HttpUtil.post(webSystemIP + "/face/base64ToJpgComparison", parameterMap, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

    /**
     * 上传临时图片
     * @param base64File
     * @return
     */
    @RequestMapping("/upLoadBase64Jpg")
    public Object upLoadBase64Jpg(@RequestParam String base64File){
        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("imgStr", base64File);
//        Response response = Http.post2(webSystemIP + "/fileupload/base64toJpg", parameterMap, 1000 * 60);
//        Result result = Json.fromJson(Result.class, response.getContent());
        try{
            String result = HttpUtil.post(webSystemIP + "/fileupload/base64toJpg", parameterMap, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

    /**
     * 工友人脸对比
     * @param wId
     * @param face
     * @return
     */
    @PostMapping("/faceComparison")
    public Object faceComparison(@RequestParam String wId,@RequestParam String face){
        // https://pre.buildoncloud.cn/workerman/face/getBase64ByFile

        try {
            Map<String, Object> parameterMap1 = new HashMap<>();
            parameterMap1.put("id", wId);
            String base64File = HttpUtil.post(webSystemIP + "/face/getBase64ByFile", parameterMap1, 1000 * 60);

            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> readValueMap = objectMapper.readValue(base64File, HashMap.class);
            if (readValueMap == null){
                return Result.error(Constant.API_INTERFASE_ERROR);
            }
            Integer code = Integer.parseInt(readValueMap.get("code").toString());
            if (code > 0) {
                return base64File;
            }

            String face1 = readValueMap.get("data").toString();

            Map<String, Object> parameterMap2 = new HashMap<>();
            parameterMap2.put("face1", face1);
            parameterMap2.put("face2", face);
            String resultStr = HttpUtil.post(webSystemIP + "/face/base64ToJpgComparison", parameterMap2, 1000 * 60);

            Result result = objectMapper.readValue(resultStr, Result.class);

            if (result.getCode() > 0){
                return resultStr;
            }

            Map<String, Object> parameterMap3 = new HashMap<>();
            parameterMap3.put("imgStr", face);
            String faseFilePath = HttpUtil.post(webSystemIP + "/fileupload/base64toJpg", parameterMap3, 1000 * 60);
            Map<String, Object> readValueMap3 = objectMapper.readValue(faseFilePath, HashMap.class);
            if (readValueMap3 == null){
                return Result.error(Constant.API_INTERFASE_ERROR);
            }
            Integer code3 = Integer.parseInt(readValueMap3.get("code").toString());
            if (code3 > 0){
                return faseFilePath;
            }
            String photoPath = readValueMap3.get("data").toString();


            Map<String, Object> headPhotoMap = workerManService.getWorkerManHeadPhotoById(Long.parseLong(wId));
            Double data = (Double) result.getData();
            Map<String, Object> map = new HashMap<>();
            map.put("difference", data);
            map.put("face1_photo_id", headPhotoMap.get("head_photo_id"));
            map.put("photoPath", photoPath);
            result.setData(map);
            return result;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return Result.error(Constant.API_INTERFASE_ERROR);
    }

    /**
     * 工友人脸修改
     * @param pId
     * @param wId
     * @param photoPath
     * @return
     */
    @PostMapping("/updateFaceByWorkerMan")
    public Object updateFaceByWorkerMan(@RequestParam String pId, @RequestParam String wId,@RequestParam String photoPath){
        try{

            Map<String, Object> parameterMap2 = new HashMap<>();
            parameterMap2.put("projectId", pId);
            parameterMap2.put("workerManId", wId);
            parameterMap2.put("photoPath", photoPath);
            String result = HttpUtil.post(webSystemIP + "/business/workerman/updateFaceByWorkerMan", parameterMap2, 1000 * 60);

            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return Result.error(Constant.API_INTERFASE_ERROR);
    }



}
